package com.tetris.entities;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import static com.tetris.util.Constants.*;

public class Shape {
	
	public Shape(){
		Random random = new Random();
		// 生成随机颜色
		int r = random.nextInt(255);
		int g = random.nextInt(255);
		int b = random.nextInt(255);
		// 排除浅色
		// 由于背景色是 0x00f9ed，所以还需要排除背景色
		if(r < 100) r += 100;
		if(g > 0xdd) g -= 0xdd;
		if(g < 100) g += 50;
		if(b > 0xad) b -= 0xad;
		if(b < 100) b += 50;

		this.color = new Color(r, g, b);
	}
	
	private ShapeData shapeData;	//	生产的图形的数据
	private int status;			//  图形的状态索引
	private int top;	//	图形的top坐标
	private int left;   //	图形的left坐标
	private Color color;

	public final static int ROTATE	= 0;	// 变换
	public final static int RIGHT	= 1;
	public final static int LEFT 	= 2;
	public final static int DOWN 	= 3;

	public void moveLeft(){
		left--;
	}
	
	public void moveRight(){
		left++;
	}
	
	public void moveDown(){
		top++;
	}
		
	public void moveDown(int offset){
		top = top + offset;
	}

	public void rotate(){
		status = (status+1)%shapeData.getData().length;
		if(left<0){
			left = 0;
		}
		if(left + shapeData.getShapeSize() >= GAME_WIDTH){
			left = GAME_WIDTH - shapeData.getShapeSize();
		}
	}
	
	public void drawShape(Graphics g){
		g.setColor(this.color);
		int[][] data = shapeData.getData()[status];
		for (int x = 0; x < data.length; x++) {
			for (int y = 0; y < data[x].length; y++) {
				if(isMember( x, y )){
					g.fill3DRect(( x + left ) * CELL_Size, 
								 ( y + top ) * CELL_Size, 
								 CELL_Size, CELL_Size, true);
				}
			}
		}
	}
	
	/** 判断该坐标是否是图形的一部分 */
	public Boolean isMember(int x, int y){
		return shapeData.getData()[status][x][y] == 1;
	}

	public void setShapeData(ShapeData data){
		this.shapeData = data;
		// 默认初始居中下落
		this.left = (GAME_WIDTH - data.getShapeSize())/2;
		top = shapeData.getShapeSize() * -1;
	}

	public ShapeData getShapeData(){
		return this.shapeData;
	}

	public int[][] getData(){
		return shapeData.getData()[status];
	}
	
	public void setStatus(int status){
		this.status = status;
	}
	
	public int getTop(){
		return this.top;
	}
	
	public int getLeft(){
		return this.left;
	}

	public Color getColor() {
		return this.color;
	}
}
